<template>

    <Pay :payClick="payClick" :money="orderMoney" :goBack="goBack"></Pay>
    
</template>
<script>
import Pay from "../../../real-components/Pay";
import md5 from "js-md5";
import axios from "axios";
import {mapGetters} from "vuex";
import * as api from "../../../api/gw/index.js";
import {Toast} from "../../../utils/toast";
import getOrderInfo from "../../../api/gw/getOrderInfo";
import {showLoading, hideLoading} from "../../../utils/loading.js";

export default {
    props: {

    },
    data() {
        return {
            orderMoney: 0,
            // orderType: 2,//默认为2，跳到订单列表的待配送状态
            payClick: () => {}
        }
    },
    computed: {
        money () {
            //如果当前页面金额错误跳回个人中心
            if (this.$route.params.money < 0 || this.$route.params.money === undefined) {
                this.$router.replace("profile");
                return;
            }
            return this.$route.params.money;
        },
        orderNo () {
            //获取订单编号
            return this.$route.params.orderNo;
        },
        //订单类型，线上订单为2（跳转到待配送），线下订单为1（跳转到全部）
        orderType() {
            return this.$route.params.orderType ? this.$route.params.orderType : 2;
        }
    },
    components: {
        Pay,
    },
    methods: {
        goBack() {
            //订单类型，线上订单为2（跳转到待支付），线下订单为1（跳转到全部）
            if (this.orderType === 2) {
                //线上订单为2（跳转到待支付）
                this.$router.replace({"name": "order", query: {orderStatus: 1}});
            } else if(this.orderType === 1) {
                //线下订单为1（跳转到全部）
                this.$router.replace({"name": "order", query: {orderStatus: 0}});
            }
        },
        init() {
            
            // console.log(1111111111);
            var that = this;
            var pay_no = '';
            var created_ts = '';
            var se_sign = '';
            var use_json = '0';
            var amount = ''
            var SEPayPlugin_Start = function (pay_no,created_ts,se_sign,amount){
                // alert("start to pay 1. ");
                //初始化
                cordova.require('cordova/channel').onCordovaReady.subscribe(function() {
                    //  在安卓 进入后 在注册这个方法的时候 和安卓那边就已经调用这个方法了；
                    // alert("start to pay 2, exec SEPayPlugin  ");
                    cordova.exec(null, null, 'SEPayPlugin',null, []);
                    //CenterCommandPlugin('start');
                    doPay(pay_no,created_ts,se_sign,amount);
                });
            }
            var doPay = function  (pay_no,created_ts,se_sign,amount){ 
                var data = {
                    pay_no: pay_no,
                    created_ts: created_ts,
                    se_sign: se_sign,
                    use_json: '0',
                    order_money: amount
                }
                var pay = "sePay" + JSON.stringify(data)
                    SEPayPlugin(pay,
                        function(){
                            // setTimeout(() => {
                                that.$router.replace({"name": "paysuccessfully", params: {orderType: that.orderType}});
                            // }, 1600);
                        },
                        function (){
                            console.log("支付失败");
                            Toast({
                                message: '支付失败',
                                type: "fail",
                                duration: 1600
                            });
                    });
            }
            var SEPayPlugin =  function  (params,sucFunc,failFunc,opts, className) {
                var params = params || null;
                var sucFunc = sucFunc || function(){};
                var failFunc = failFunc || function(){};
                var opts = opts || {};
                var className = className || null ;
                
                try{
                    cordova.exec(sucFunc,failFunc, "SEPayPlugin", "start", [className, params,opts]) ;
                }
                catch(err){
                    alert("如您在app中进行支付，程序调起支付app失败，请点击按钮手动尝试下！")
                }
            }

            this.payClick = function() {
            	//判断配送时间是否合法
            	
            	let callback = () => {
            		if (that.orderMoney > 0) {
	                    // 请求java接口，请求前判断用户使用余额情况 判断是否需要调起翌支付
	                    var sessionId = localStorage.getItem('sessionId');
	                    // var sessionId = "c15e7bff7d3944a59ac7b0461c328430";
	                    //订单编号
	                    var orderNo = that.orderNo;
	                    //
	                    var scenary_id = "3";
	                    let options = {
	                        method: "post",
	                        // url: window.api.local_host + api.gwPay,
	                        url: window.api.trade_host + api.gwPay,
	                        data: {
	                            sessionId,
	                            "bill_id": orderNo,
	                            scenary_id
	                        }
	                    }
	                    axios(options).then(data => {
	                        // console.log(data.toString());
	                        if (data.status === 200) {
	                            // console.log(2222222222222);
	                            // alert(data.toString());
	                            var listData = data.data.data[0];
	                            if (listData != null) {
	                                var pay_no = listData.pay_no;  //
	                                var app_code = listData.app_code;
	                                var se_payment_code = listData.se_payment_code;
	                                var se_private_key = listData.se_private_key;
	                                var created_ts = Date.parse(new Date())/1000;  //
	                                var amount = listData.amount;
	                                var appStr = app_code + se_payment_code + pay_no + created_ts;
	                                var semd5 = md5(appStr) + se_private_key;
	                                var se_sign = md5(semd5); //
	                                //alert("开始支付,pay_no="+pay_no+"\r\nse_payment_code="+se_payment_code+
	                                //"\r\nse_private_key="+se_private_key+"\r\n");
	                                // alert(333333333333);
	                                SEPayPlugin_Start(pay_no,created_ts,se_sign,amount)
	                                
	                            } else {
	                                alert("请求支付失败");
	                                console.log("支付失败");
	                                //跳转到登陆页面
	                            }
	                        }
	                    });
	                } else if (that.orderMoney === 0) {
	                	//如果实付金额为0，则直接跳到支付成功页面
	                    that.$router.replace({"name": "paysuccessfully", params: {orderType: that.orderType}});
	                } else if (that.orderMoney === "fail") {
	                    Toast({
	                        message: '订单信息失效',
	                        type: "fail",
	                        duration: 1000
	                    });
	                    return;
	                }
            	}
                
                
                that.getTimeRight(callback);
            }

            
        },
        //从后台获取订单相关信息
        getOrderInfoFromApi() {
            showLoading();
            if (this.orderNo) {
                let callback = data => {
                    console.log(data);
                    this.orderMoney = parseFloat(data.realPay);
                    // this.orderMoney = 0;
                    this.orderType = 2;
                    this.init();
                    hideLoading();
                }
                //获取订单信息失败的回调
                let errFn = () => {
                    this.orderMoney = "fail";
                }
                getOrderInfo(this.orderNo, callback, errFn);
            } else {
                hideLoading();
                //跳回个人中心
                this.$router.replace("profile");
            }
        },
         //判断是否在可配送时间内
        getTimeRight(callback){
			console.log("ooo");
			let url = window.api.trade_host + '/orderDeliveryPool/checkCanToPay/' + this.orderNo;
			var sessionId = localStorage.getItem('sessionId');
			console.log(url,'链接地址')
			let config = {
            	url:url,
            	method: 'GET',
            	headers: {'sessionId': sessionId},
            };
            axios(config).then((res) => {
            	console.log(res.data.returnCode,'返回参数');
//          	console.log(res.data.returncode == 1);
//          	returnCode 0  是修改时间   1 是去支付
            	if(res.data.returnCode == 0){
            		console.log(5566);
					this.$router.push({name:'changeOrderTime',query:{orderNo:this.orderNo}});
            	} else if (res.data.returnCode === 1) {
            		callback && callback();
            	}
            })
        }
    },
    created () {
        console.log("这是ios界面1111");
        // console.log(this.$route.params);
        this.getOrderInfoFromApi();
    },
    beforeDestroy () {
        hideLoading();
    }

}
</script>

<style>

</style>


